package com.chushouya.product.dao.repository;

import com.general.framework.core.lang.Longs;
import com.general.framework.core.lang.Strings;
import com.general.framework.core.schema.PageResult;
import com.general.framework.data.mybatis.BaseRepository;
import com.chushouya.product.dao.entity.VisitDeviceEntity;
import com.chushouya.product.dao.mapper.VisitDeviceEntityMapper;
import com.chushouya.product.dto.api.visitdevice.VisitDeviceQuery;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Repository;
import tk.mybatis.mapper.entity.Example;

import java.util.List;

/**
 * 访问设备数据访问层
 * 
 * @author chushouya
 */
@Repository
@Slf4j
public class VisitDeviceRepository extends BaseRepository<VisitDeviceEntityMapper, VisitDeviceEntity, Long> {
    
    /**
     * 更新设备访问次数
     * 
     * @param deviceId 设备ID
     */
    public void incrementVisitCount(Long deviceId) {
        if (deviceId == null) {
            return;
        }
        
        VisitDeviceEntity entity = this.selectByPrimaryKey(deviceId);
        if (entity != null) {
            entity.setVisitCount(entity.getVisitCount() == null ? 1 : entity.getVisitCount() + 1);
            this.updateByPrimaryKeySelective(entity);
        }
    }

    public List<VisitDeviceEntity> selectList(VisitDeviceQuery query) {
        return selectByExample(buildExample(query));
    }

    public PageResult<VisitDeviceEntity> selectPage(VisitDeviceQuery query) {
        return this.selectPage(query.getPageRequest(), this.buildExample(query));
    }

    public VisitDeviceEntity selectOne(VisitDeviceQuery query) {
        return selectFirstOneByExample(buildExample(query));
    }



    private Example buildExample(VisitDeviceQuery query) {
        Example example = this.buildExample();
        if (Longs.notNullAndZero(query.getProductId())) {
            example.and().andEqualTo("productId", query.getProductId());
        }
        if (Strings.isNotEmpty(query.getDeviceName())) {
            example.and().andEqualTo("deviceName", query.getDeviceName());
        }
        if (Strings.isNotEmpty(query.getDeviceBrand())) {
            example.and().andEqualTo("deviceBrand", query.getDeviceBrand());
        }
        if (Strings.isNotEmpty(query.getDeviceSystem())) {
            example.and().andEqualTo("deviceSystem", query.getDeviceSystem());
        }
        if (Strings.isNotEmpty(query.getProductName())) {
            example.and().andEqualTo("productName", query.getProductName());
        }
        return example;

    }
}
